package com.qd.panda.service.plate;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.excel.ExcelExport;
import com.cdqidi.excel.util.ExportPage;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.panda.domain.entity.plate.PlateDTO;
import com.qd.common.panda.domain.entity.plate.UserPlateRelationDTO;
import com.qd.common.panda.util.PlateColorUtil;
import com.qd.common.sys.util.SecurityUtils;
import com.qd.hik.dto.HkBaseHttpResp;
import com.qd.hik.dto.driver.HkPlateReq;
import com.qd.hik.dto.driver.HkPlateResp;
import com.qd.hik.service.HkDriverService;
import com.qd.panda.mapper.plate.UserPlateRelationMapper;
import com.qd.panda.mapper.space.ParkSpaceTenantMapper;
import com.qd.panda.model.HkUser;
import com.qd.panda.model.Plate;
import com.qd.panda.model.UserPlateRelation;
import com.qd.panda.service.third.hk.HkUserService;
import com.qd.system.service.dict.MbUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * 用户和车牌关系
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class UserPlateRelationService extends BaseService<UserPlateRelationMapper, UserPlateRelation> {

    private static final String PLATE_NUMBER = "plate_number";
    private static final String PREFIX_ID = "panda_user_plate_relation_rId_{0}";
    private static final String PREFIX_USER_ID = "panda_user_plate_relation_userId_{0}";
    private static final String PREFIX_UNIQUE_PANDA_USER = "panda_user_plate_relation_plateNumber_{0}";

    private final RedisTemplateUtil<UserPlateRelation> redisTemplateUtil;
    private final PlateService plateService;
    private final HkDriverService hkDriverService;
    private final HkUserService hkUserService;

    @Resource
    private HttpServletResponse response;
    @Resource
    private ParkSpaceTenantMapper parkSpaceTenantMapper;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserPlateRelationDTO save(UserPlateRelationDTO dto) {
        checkUnique(dto);
        final UserPlateRelation model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserPlateRelationDTO update(UserPlateRelationDTO dto) {
        checkUnique(dto);
        final UserPlateRelation historyModel = Optional.ofNullable(getById(dto.getRId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final UserPlateRelation model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            clearCache(model);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 删除，单个
     *
     * @param rId 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String rId) {
        final UserPlateRelation model = Optional.ofNullable(getById(rId)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            HkUser hkUser = hkUserService.getById(model.getUserId());
            if (null != hkUser) {
                HkBaseHttpResp<HkPlateResp> platesResp = hkDriverService.plates(hkUser.getDriverId());
                if (platesResp.isSuccess()) {
                    HkPlateResp data = platesResp.getData();
                    if(null !=data){
                        List<HkPlateResp.PlateInfo> results = data.getResults();
                        if(null !=results && !results.isEmpty()){
                            List<String> plates = results.stream().map(HkPlateResp.PlateInfo::getPlateNo).collect(toList());
                            if(plates.contains(model.getPlateNumber())){
                                HkPlateReq req = new HkPlateReq();
                                req.setDriverId(hkUser.getDriverId());
                                req.setPlateNo(model.getPlateNumber());
                                Plate plate = plateService.getById(model.getPlateNumber());
                                if (null != plate) {
                                    req.setPlateColor(PlateColorUtil.pandaToHk(plate.getVehicleColor()));
                                }
                                HkBaseHttpResp<?> resp = hkDriverService.delPlate(req);
                                req.freeData();
                                if (!resp.isSuccess()) {
                                    throw new ApiException("删除用户车牌失败");
                                }
                            }
                        }
                    }
                } else {
                    throw new ApiException("获取车牌号异常");
                }
            }
            if (SqlHelper.retCount(parkSpaceTenantMapper.existsByTenantNumber(model.getPlateNumber(), LocalDate.now())) > 0) {
                throw new ApiException("存在未结束的租赁订单,不能删除");
            }
            if (!super.removeById(rId)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        ids.forEach(this::removeById);
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(UserPlateRelationDTO dto) {
        final QueryWrapper<UserPlateRelation> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param rId 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String rId) {
        boolean exists = false;
        if (StringUtils.hasLength(rId)) {
            final UserPlateRelation model = getById(rId);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param rId 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserPlateRelation getById(String rId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, rId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(rId), UserPlateRelation.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param rId 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserPlateRelationDTO getByIdDto(String rId) {
        return Optional.ofNullable(getById(rId)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserPlateRelation getOne(UserPlateRelationDTO dto) {
        final QueryWrapper<UserPlateRelation> queryWrapper = createQueryWrapper(dto);
        UserPlateRelation model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserPlateRelationDTO getOneDto(UserPlateRelationDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<UserPlateRelation> getList(UserPlateRelationDTO dto) {
        final QueryWrapper<UserPlateRelation> queryWrapper = createQueryWrapper(dto);
        queryWrapper.orderByAsc(PLATE_NUMBER);
        final List<UserPlateRelation> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<UserPlateRelationDTO> getListDto(UserPlateRelationDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<UserPlateRelationDTO> page(Page<UserPlateRelation> page, UserPlateRelationDTO dto) {
        final QueryWrapper<UserPlateRelation> queryWrapper = createQueryWrapper(dto, "uc.");
        queryWrapper.orderByDesc("uc.add_time");
        final IPage<UserPlateRelationDTO> iPage = baseMapper.page(page, queryWrapper);
        final List<UserPlateRelationDTO> records = iPage.getRecords();
        if (!records.isEmpty()) {
            records.forEach(this::buildDisplay);
        }
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<UserPlateRelationDTO> webPage(Page<UserPlateRelation> page, UserPlateRelationDTO dto) {
        final QueryWrapper<UserPlateRelation> queryWrapper = new QueryWrapper<>();
        if(StringUtils.hasLength(dto.getPlateNumber())){
            queryWrapper.like("t1.plate_number", dto.getPlateNumber());
        }
        if(StringUtils.hasLength(dto.getMobile())){
            queryWrapper.like("t2.mobile", dto.getMobile());
        }
        queryWrapper.orderByDesc("t1.add_time");
        final IPage<UserPlateRelationDTO> iPage = baseMapper.webPage(page, queryWrapper);
        final List<UserPlateRelationDTO> records = iPage.getRecords();
        if (!records.isEmpty()) {
            records.forEach(this::buildDisplay);
        }
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 导出Excel
     *
     * @param query 查询条件
     * @throws IOException 异常
     */
    @Transactional(readOnly = true)
    public void export(UserPlateRelationDTO query) throws IOException {
        final ExportPage<UserPlateRelation, UserPlateRelationDTO> exportPage = new ExportPage<>();
        final List<UserPlateRelationDTO> list = exportPage.getAllForPage(page -> page(page, query).getRecords());
        try {
            ExcelExport.downloadExcel(response, UserPlateRelationDTO.class, () -> list);
        } catch (IOException e) {
            log.error("导出失败", e);
            throw new ApiException("导出失败");
        }
    }

    @Transactional(readOnly = true)
    public String getPlateNumberByUserId(String userId) {
        final List<UserPlateRelation> plateList = getUserPlateRelationByUserId(userId);
        if (!plateList.isEmpty()) {
            final UserPlateRelation userPlateRelation = plateList.get(0);
            return userPlateRelation.getPlateNumber();
        }
        return null;
    }

    @Transactional(readOnly = true)
    public List<UserPlateRelation> getUserPlateRelationByUserId(String userId) {
        final QueryWrapper<UserPlateRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_USER_ID, userId);
        final List<UserPlateRelation> model = redisTemplateUtil.getList(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> getBaseMapper().selectList(queryWrapper), UserPlateRelation.class);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据唯一性索引获得数据
     * <p>
     * param plateNumber
     *
     * @return 单条数据
     */
    @Transactional(readOnly = true)
    public UserPlateRelation getUniqueByPlateNumber(String plateNumber) {
        final QueryWrapper<UserPlateRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(PLATE_NUMBER, plateNumber);
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_USER, plateNumber);
        final UserPlateRelation model = redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getOne(queryWrapper, false), UserPlateRelation.class);
        queryWrapper.clear();
        return model;
    }

    /**
     * 验证唯一性索引
     *
     * @param dto 页面对象
     */
    @Transactional(readOnly = true)
    public void checkUnique(UserPlateRelationDTO dto) {
        UserPlateRelation model = getUniqueByPlateNumber(dto.getPlateNumber());
        if (null != model) {
            checkUnique(dto, model);
        }
    }

    /**
     * 验证唯一性索引
     *
     * @param dto   页面对象
     * @param model 根据约束字段查询出来的数据库对象
     */
    private void checkUnique(UserPlateRelationDTO dto, UserPlateRelation model) {
        if (!StringUtils.hasLength(dto.getRId())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
        if (!dto.getRId().equals(model.getRId())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(UserPlateRelation model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getRId()));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_USER_ID, model.getUserId()));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_USER, model.getPlateNumber()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<UserPlateRelation> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getRId())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
        List<String> userIds = list.stream().filter(model -> StringUtils.hasLength(model.getUserId())).map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_USER_ID, model.getUserId())).collect(toList());
        if (!userIds.isEmpty()) {
            redisTemplateUtil.deleteByKey(userIds);
            userIds.clear();
        }
        List<String> plateNumberList = list.stream().filter(model -> StringUtils.hasLength(model.getPlateNumber())).map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_USER, model.getPlateNumber())).collect(toList());
        if (!plateNumberList.isEmpty()) {
            redisTemplateUtil.deleteByKey(plateNumberList);
            plateNumberList.clear();
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public UserPlateRelationDTO modelToDto(UserPlateRelation model) {
        if (null == model) {
            return null;
        }
        final UserPlateRelationDTO dto = new UserPlateRelationDTO();
        dto.setRId(model.getRId());
        dto.setPlateNumber(model.getPlateNumber());
        dto.setUserId(model.getUserId());
        dto.setAutoConfirmCharge(model.getAutoConfirmCharge());
        dto.setAddTime(model.getAddTime());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public UserPlateRelation dtoToModel(UserPlateRelationDTO dto) {
        if (null == dto) {
            return null;
        }
        final UserPlateRelation model = new UserPlateRelation();
        model.setRId(dto.getRId());
        model.setPlateNumber(dto.getPlateNumber());
        model.setUserId(dto.getUserId());
        model.setAutoConfirmCharge(dto.getAutoConfirmCharge());
        model.setAddTime(dto.getAddTime());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(UserPlateRelationDTO dto) {
        dto.setAutoConfirmChargeDisplay(MbUtil.idToDisplay(dto.getAutoConfirmCharge()));
        final PlateDTO plateDTO = plateService.getByIdDto(dto.getPlateNumber());
        if (null != plateDTO) {
            dto.setPlate(plateDTO);
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<UserPlateRelationDTO> modelToDtoList(List<UserPlateRelation> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<UserPlateRelation> dtoToModelList(List<UserPlateRelationDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<UserPlateRelation> createQueryWrapper(UserPlateRelationDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<UserPlateRelation> createQueryWrapper(UserPlateRelationDTO dto, String tableAlias) {
        final QueryWrapper<UserPlateRelation> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias)) {
                if (tableAlias.charAt(tableAlias.length() - 1) != '.') {
                    tableAlias += ".";
                }
            }
            if (StringUtils.hasLength(dto.getPlateNumber())) {
                queryWrapper.eq(tableAlias + PLATE_NUMBER, dto.getPlateNumber());
            }
            if (StringUtils.hasLength(dto.getUserId())) {
                queryWrapper.eq(tableAlias + "user_id", dto.getUserId());
            }
        }
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     */
    public List<UserPlateRelation> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<UserPlateRelation> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(UserPlateRelation::getRId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    @Transactional(readOnly = true)
    public boolean checkPlateNumber(String plateNumber) {
        final String userId = SecurityUtils.getLoginUser().getUserId();
        return checkPlateNumber(userId, plateNumber);
    }

    @Transactional(readOnly = true)
    public boolean checkPlateNumber(String userId, String plateNumber) {
        final List<UserPlateRelation> list = getUserPlateRelationByUserId(userId);
        return list.stream().anyMatch(userPlateRelation -> userPlateRelation.getPlateNumber().equals(plateNumber));
    }
}